"""MCP Server: 暴露 ThingsBoard 三个操作供 AI 调用。

工具:
- list_devices
- get_device_alarms(device_id)
- get_latest_telemetry(device_id)
- acknowledge_alarm(alarm_id)
- clear_alarm(alarm_id)

运行:
python server.py
然后根据 MCP 框架集成到上层 AI 客户端。
"""
from __future__ import annotations
from mcp.server.fastmcp import FastMCP
from thingsboard_client import ThingsBoardClient, ThingsBoardError
import typing as t

mcp = FastMCP("thingsboard")
client = ThingsBoardClient()

@mcp.tool()
def list_devices() -> list[dict]:
    """获取全部设备(最多100条，可扩展分页)。"""
    devices = client.list_devices()
    return [device.__dict__ for device in devices]

@mcp.tool()
def get_device_alarms(device_id: str) -> list[dict]:
    """获取指定设备的全部告警(第一页最多100条)。"""
    alarms = client.get_device_alarms(device_id)
    return [alarm.__dict__ for alarm in alarms]

@mcp.tool()
def get_latest_telemetry(device_id: str) -> list[dict]:
    """获取指定设备最新遥测(每个key最新一条)。"""
    telemetry = client.get_latest_telemetry(device_id)
    return [t.__dict__ for t in telemetry]


@mcp.tool()
def acknowledge_alarm(alarm_id: str) -> dict:
    """确认指定告警。"""
    client.acknowledge_alarm(alarm_id)
    return {"alarmId": alarm_id, "status": "acknowledged"}


@mcp.tool()
def clear_alarm(alarm_id: str) -> dict:
    """消除指定告警。"""
    client.clear_alarm(alarm_id)
    return {"alarmId": alarm_id, "status": "cleared"}

if __name__ == "__main__":
    # FastMCP 默认运行 uvicorn 风格 server
    mcp.run()
